from celery import Celery
from app.core.config import settings

celery_app = Celery(
    "thrush_ai",
    broker=settings.REDIS_URL,
    backend=settings.REDIS_URL,
    include=[
        "app.tasks.generation_tasks",
        "app.tasks.image_generation_tasks", 
        "app.tasks.template_video_tasks"
    ]
)

celery_app.conf.update(
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="UTC",
    enable_utc=True,
    task_track_started=True,
    task_routes={
        "app.tasks.generation_tasks.*": {"queue": "generation"},
        "app.tasks.generation_tasks.generate_video_async": {"queue": "jimeng_video"},  # 即梦AI视频生成专用队列
        "generate_image_async": {"queue": "jimeng_image"},  # 即梦AI图片生成专用队列  
        "template_to_video_combined": {"queue": "jimeng_template"},  # 即梦AI模板生视频专用队列
    },
    # 队列配置 - 针对即梦AI并发限制=1
    task_default_queue="default",
    task_default_exchange="default",
    task_default_exchange_type="direct",
    task_default_routing_key="default",
    # 即梦AI队列并发限制
    worker_prefetch_multiplier=1,  # 每个worker一次只处理一个任务
    task_acks_late=True,  # 任务完成后才确认
    worker_disable_rate_limits=False,
    # 任务超时设置
    task_soft_time_limit=600,  # 10分钟软超时
    task_time_limit=900,   # 15分钟硬超时
)

from celery.signals import worker_process_init
from app.core.service_init import initialize_all_services
import logging

@worker_process_init.connect
def init_services(**kwargs):
    """
    Celery Worker进程启动时初始化所有服务
    """
    logger = logging.getLogger(__name__)
    logger.info("Celery Worker 进程启动，开始初始化AI服务...")
    try:
        initialize_all_services()
        logger.info("AI服务初始化完成")
    except Exception as e:
        logger.error(f"Celery Worker AI服务初始化失败: {e}")
